package com.ghy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ghy.dto.ReportInsertDTO;
import com.ghy.dto.ReportPageDTO;
import com.ghy.dto.ReportUpdateDTO;
import com.ghy.entity.Report;
import com.ghy.entity.User;
import com.ghy.feign.UserFeign;
import com.ghy.result.Result;
import com.ghy.vo.ReportSimpleListVO;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ghy.entity.Report;
import com.ghy.mapper.ReportMapper;
import com.ghy.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

import static com.ghy.entity.table.CommentTableDef.COMMENT;
import static com.ghy.entity.table.ReportTableDef.REPORT;

/**
 * 举报表 服务层实现。
 *
 * @author ghy
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "report")
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report>  implements ReportService{


    @Autowired
    private UserFeign userFeign;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(ReportInsertDTO dto) {
        //组装entity 实体类
        Report report = BeanUtil.copyProperties(dto, Report.class);
        User user = userFeign.select(dto.getFkUserId()).getData();
        if (ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        report.setNickname(user.getNickname());
        report.setCreated(LocalDateTime.now());
        report.setUpdated(LocalDateTime.now());

        return mapper.insert(report) > 0;
    }

    @Cacheable(key = "#p0",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public Report select(Long id) {
        RelationManager.addQueryRelations("episode");
        return mapper.selectOneWithRelationsById(id);
    }

    @Cacheable(key = "#root.methodName",
            unless = "#result == null")
    @Override
    public List<ReportSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .withRelations ()
                .listAs(ReportSimpleListVO.class);
    }

    @Cacheable(key ="#root.methodName + ':' + #p0.toString()",
            condition = "#p0 != null",
            unless = "#result == null")
    @Override
    public Page<Report> page(ReportPageDTO dto) {
        QueryChain<Report> queryChain = QueryChain.of(mapper);



        //episodeId条件
        Long episodeId = dto.getFkEpisodeId();
        if (ObjectUtil.isNotNull(episodeId)){
            queryChain.where(REPORT.FK_EPISODE_ID.eq(episodeId));
        }

        //userId条件
        Long userId = dto.getFkUserId();
        if (ObjectUtil.isNotNull(userId)){
            queryChain.where(REPORT.FK_USER_ID.eq(userId));
        }

        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(),dto.getPageSize()));
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean update(ReportUpdateDTO dto) {
        //组装entity实体类
        Report report = BeanUtil.copyProperties(dto, Report.class);
        Result<User> user = userFeign.select(dto.getFkUserId());
        if (ObjectUtil.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        report.setNickname(user.getData().getNickname());
        report.setUpdated(LocalDateTime.now());

        return UpdateChain.of(report)
                .where(REPORT.ID.eq(report.getId()))
                .update();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {

        //删除父评论
        return mapper.deleteById(id) > 0;

    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {

        //删除父评论
        return mapper.deleteBatchByIds(ids) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteByUserId(Long userId){
        return UpdateChain.of(mapper)
                .where(REPORT.FK_USER_ID.eq(userId))
                .remove();
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteByUserIds(List<Long> userIds){
        return UpdateChain.of(mapper)
                .where(REPORT.FK_USER_ID.in(userIds))
                .remove();
    }
}
